#include "led_motor_control.h"

#define MOTOR_PWM_DEFAULT_DUTY  2   //默认占空比
#define PWM_CLK_FREQ 160000000      //PWM频率
#define freq 2442  //min
unsigned int Led_Status;
unsigned int Motor_Status;


/*
    函数：电机，LED引脚初识化函数
*/
void Led_Motor_Init(void)
{
    // 初识化电机引脚
    int ret = -1;
    ret = hi_pwm_deinit(HI_PWM_PORT_PWM2);
    if(ret != 0){ 
        printf("hi_pwm_deinit failed :%x \r\n",ret); 
        return;
    }

    ret = hi_pwm_init(HI_PWM_PORT_PWM2);
    if(ret != 0){ 
        printf("hi_pwm_init failed :%x \r\n",ret); 
        return;
    }

    ret = hi_pwm_set_clock(PWM_CLK_160M);
    if(ret != 0){ 
        printf("hi_pwm_set_clock failed ret : %x \r\n",ret); 
        return;
    }

    // 初识化LED引脚
    ret = hi_io_set_func(HI_IO_NAME_GPIO_6, HI_IO_FUNC_GPIO_6_GPIO);
    if (ret != HI_ERR_SUCCESS) {
        printf("===== ERROR ===== gpio -> hi_io_set_func ret:%d\r\n", ret);
        return;
    }
    printf("----- io set func success-----\r\n");

    ret = hi_gpio_set_dir(HI_GPIO_IDX_6, HI_GPIO_DIR_OUT);
    if (ret != HI_ERR_SUCCESS) {
        printf("===== ERROR ===== gpio -> hi_gpio_set_dir1 ret:%d\r\n", ret);
        return;
    }
}

/*
    功能：电机PWM驱动函数
*/
static void motor_pwm_start(unsigned int duty)
{
    int ret = 0;  
    printf("motor start \r\n");
    printf("func: %s, duty : %d\r\n",__func__,duty);
    
    if(duty == 0){
        ret = hi_pwm_stop(HI_PWM_PORT_PWM2); 
        if(ret != 0){ 
            printf("hi_pwm_start failed ret : %#x \r\n",ret); 
        }
    }

    ret = hi_pwm_start(HI_PWM_PORT_PWM2, duty*(PWM_CLK_FREQ/freq)/100, PWM_CLK_FREQ/freq); 
    if(ret != 0){ 
        printf("hi_pwm_start failed ret : %#x \r\n",ret); 
    }
}

/*
    功能：LED控制函数
*/
void Led_Control(int led_status)
{
    Led_Status = led_status;
    printf("func: %s, on : %d\r\n",__func__,led_status);
    led_status == 1?hi_gpio_set_ouput_val(HI_GPIO_IDX_6,HI_GPIO_VALUE1):\
        hi_gpio_set_ouput_val(HI_GPIO_IDX_6,HI_GPIO_VALUE0);
}

/*
    功能：电机控制函数
*/
void Motor_Control(int motor_status)
{
    Motor_Status = Motor_Status;
    printf("func: %s, on : %d\r\n",__func__,motor_status);
    motor_status == 1 ? motor_pwm_start(MOTOR_PWM_DEFAULT_DUTY):\
        hi_pwm_stop(HI_PWM_PORT_PWM2);
}

unsigned int Led_Get_Status(void){
    return Led_Status;
}
unsigned int Motor_Get_Status(void){
    return Motor_Status;
}